<template>
	<view class="wrap">
		<view class="top">
			<view class="item">
				<view class="left">收货人</view>
				<input v-model="userName" type="text" placeholder-class="line" placeholder="请填写收货人姓名" />
			</view>
			<view class="item">
				<view class="left">手机号码</view>
				<input v-model="phone" type="text" placeholder-class="line" placeholder="请填写收货人手机号" />
			</view>
			<view class="item">
				<view class="left">所在地区</view>
				<input v-model="address" @tap="show = true" disabled type="text" placeholder-class="line" placeholder="省市区县、乡镇等" />
			</view>

			<view class="item address">
				<view class="left">详细地址</view>
				<view class="textarea">
					<u-input v-model="areaInfo" auto-height height="150" type="textarea" placeholder-class="line" placeholder="街道、楼牌等" />
				</view>
			</view>
			<view class="item" style="border-bottom: none;">
				<view class="left">定位位置</view>
				<input v-model="locationInfo" @click="choiceAddress" disabled type="text" placeholder-class="line" placeholder="请选择定位位置" />
				<u-icon name="arrow-right" color="#A5A4A4"></u-icon>
			</view>
		</view>
		<view class="bottom">
			<view class="default">
				<view class="left">
					<view class="set">设置默认地址</view>
					<view class="tips">提醒：每次下单会默认推荐该地址</view>
				</view>
				<view class="right">
					<switch :checked="isChecked" color="#FF4E46" @change="setDefault" />
				</view>
			</view>
		</view>
		<u-select safe-area-inset-bottom :default-value="defaultValue" title="选择省/市/区" confirm-color="#FF4E47" v-model="show" mode="mutil-column-auto"
		 :list="list" @confirm="confirm"></u-select>
		<u-toast ref="uToast" />
		<view class="btn">
			<view class="box" @click="submit">
				确定
			</view>
			<view class="safe-area-inset-bottom"></view>
		</view>
	</view>
</template>

<script>
	import QQMapWX from "@/common/qqmap-wx-jssdk.min";
	import WSCoordinate from '@/js_sdk/WSCoordinate'
	let qqmapsdk = ''
	export default {
		data() {
			return {
				show: false,
				userName: '',
				areaInfo: '',
				locationInfo: '',
				isChecked: false,
				defaultValue: [0, 0, 0],
				phone: '',
				list: [],
				address: ''
			}
		},
		onUnload() {
			uni.removeStorageSync('addressInfo')
		},
		onLoad(options) {
			console.log(uni.getStorageSync('addressInfo'));
			qqmapsdk = new QQMapWX({
				key: 'HQSBZ-EMKE5-6N5IW-QYGDQ-U6EMS-P2BOO'
			});
			this.type = options.type
			if (this.type == 'edit') {
				let addressInfo = uni.getStorageSync('addressInfo')
				this.longitude = addressInfo.longitude
				this.latitude = addressInfo.latitude
				this.userName = addressInfo.userName
				this.phone = addressInfo.phone
				this.areaInfo = addressInfo.address.split(' ')[1]
				this.areaId = addressInfo.areaId
				this.address = addressInfo.areaInfo
				this.isChecked = addressInfo.isChecked
				this.locationInfo = addressInfo.address.split(' ')[0]


			} else {
				let userInfo = uni.getStorageSync('userInfo')
				this.userName = userInfo.realName || ''
				this.phone = userInfo.userName
			}
			uni.setNavigationBarTitle({
				title: options.type == 'add' ? '新增地址' : '编辑地址'
			})
			const self = this
			let res = uni.getStorageSync('regionList')
			let province = res.filter(item => item.level == 1)
			let city = res.filter(item => item.level == 2)
			let area = res.filter(item => item.level == 3)
			let region = province.map(level1 => {
				return {
					label: level1.areaName,
					value: level1.id,
					parentId: level1.parentId,
					children: city.filter(level2 => level2.parentId == level1.id).map(level2 => {
						return {
							label: level2.areaName,
							value: level2.id,
							parentId: level2.parentId,
							children: area.filter(level3 => level3.parentId == level2.id).map(level3 => {
								return {
									label: level3.areaName,
									value: level3.id,
									parentId: level3.parentId,
								}
							})
						}
					})
				}
			})
			this.list = region
			let locationPermission = uni.getStorageSync('locationPermission')
			if (locationPermission) {
				this.reverseGeocoder(locationPermission.latitude, locationPermission.longitude)
			} else {
				uni.getLocation({
					type: 'gcj02',
					altitude: true,
					success(res) {
						self.reverseGeocoder(res.latitude, res.longitude)
					},
					fail() {
						uni.showToast({
							title: '定位失败了',
							icon: 'none'
						})
					}
				})
			}
		},
		methods: {
			async submit() {
				if (this.userName == '') {
					uni.showToast({
						title: '请填写收货人姓名',
						icon: 'none'
					})
					return
				}
				if (this.phone == '') {
					uni.showToast({
						title: '请填写收货人手机号',
						icon: 'none'
					})
					return
				}
				if (this.address == '') {
					uni.showToast({
						title: '请选择所在地区',
						icon: 'none'
					})
					this.show = true
					return
				}
				if (this.areaInfo == '') {
					uni.showToast({
						title: '请填写街道、楼牌等',
						icon: 'none'
					})
					return
				}
				if (this.locationInfo == '') {
					uni.showToast({
						title: '请选择定位位置',
						icon: 'none'
					})
					return
				}
				let BD_Coordinate = WSCoordinate.transformFromGCJToBaidu(this.latitude, this.longitude)
				if (this.type == 'add') {
					await this.$u.post('useraddress/save', {
						address: this.locationInfo + ' ' + this.areaInfo,
						areaInfo: this.address,
						areaId: this.areaId,
						isChecked: this.isChecked,
						latitude: BD_Coordinate.latitude,
						longitude: BD_Coordinate.longitude,
						phone: this.phone,
						userName: this.userName
					})
				} else {
					await this.$u.post('useraddress/update', {
						address: this.locationInfo + ' ' + this.areaInfo,
						areaInfo: this.address,
						areaId: this.areaId,
						id: uni.getStorageSync('addressInfo').id,
						isChecked: this.isChecked,
						latitude: BD_Coordinate.latitude,
						longitude: BD_Coordinate.longitude,
						phone: this.phone,
						userName: this.userName
					})
				}
				this.$refs.uToast.show({
					title: '操作成功',
					back: true,
					type: 'success'
				})
				var pages = getCurrentPages(); //当前页面栈
				if (pages.length > 1) {
					var beforePage = pages[pages.length - 2]; //获取上一个页面实例对象  
					beforePage.$vm.getData(); //触发父页面中的方法change()  
				}
			},
			setDefault(e) {
				this.isChecked = e.detail.value
			},
			reverseGeocoder(latitude, longitude) {
				const self = this
				qqmapsdk.reverseGeocoder({
					location: `${latitude},${longitude}`,
					success(res) {
						if (res.status == 0) {
							let {
								address_component
							} = res.result
							let provinceIndex = self.list.findIndex(item => item.label == address_component.province)
							let cityIndex = self.list[provinceIndex].children.findIndex(item => item.label == address_component.city)
							let areaIndex = self.list[provinceIndex].children[cityIndex].children.findIndex(item => item.label ==
								address_component.district)
							self.defaultValue = [provinceIndex, cityIndex, areaIndex]
						} else {
							uni.showToast({
								title: res.message,
								icon: 'none'
							})
						}
					}
				})
			},
			choiceAddress() {
				if (this.address == '') {
					uni.showToast({
						title: '请先选择所在地区',
						icon: 'none'
					})
					this.show = true
					this.chooseLocation = true
					return
				}
				const self = this
				uni.chooseLocation({
					latitude: this.latitude,
					longitude: this.longitude,
					success(res) {
						self.locationInfo = res.name
						self.chooseLocation = false
					},
					fail() {
						self.chooseLocation = false
					}
				})
			},
			confirm(e) {
				const self = this
				self.address = e[0].label + e[1].label + e[2].label
				this.areaId = e[2].value
				let provinceIndex = self.list.findIndex(item => item.label == e[0].label)
				let cityIndex = self.list[provinceIndex].children.findIndex(item => item.label == e[1].label)
				let areaIndex = self.list[provinceIndex].children[cityIndex].children.findIndex(item => item.label ==
					e[2].label)
				self.defaultValue = [provinceIndex, cityIndex, areaIndex]
				qqmapsdk.geocoder({
					address: e[0].label + e[1].label + e[2].label,
					region: e[0].label,
					success(res) {
						if (res.status == 0) {
							self.latitude = res.result.location.lat
							self.longitude = res.result.location.lng
							if (self.chooseLocation) {
								self.choiceAddress()
							}
						} else {
							uni.showToast({
								title: res.message,
								icon: 'none'
							})
						}
					}
				})
			}
		}
	};
</script>

<style lang="scss">
	.btn {
		position: fixed;
		bottom: 30rpx;
		width: 100%;
		padding: 0 20rpx;

		.box {
			font-size: 30rpx;
			line-height: 100rpx;
			color: #FFFFFF;
			text-align: center;
			background: linear-gradient(90deg, #FF3868, #FC6161);
			box-shadow: 1px 10px 15px 2px rgba(255, 78, 70, 0.3);
			border-radius: 20rpx;
		}
	}

	.region {
		height: 700rpx;

		.region-text {
			display: flex;
			align-items: center;
			border-bottom: 1rpx solid #E1E0E0;
			padding: 30rpx 0;
			padding-top: 0;

			>view {
				margin-left: 30rpx;

				&:last-child {
					color: #FF4D46;
				}
			}
		}

		.title {
			text-align: center;
			line-height: 100rpx;
			font-weight: bold;
			font-size: 36rpx;
		}

		.list {
			padding: 0 30rpx;

			.item {
				padding: 30rpx 0;
				border-bottom: 1rpx solid #E1E0E0;

				&:last-child {
					border-bottom: none;
				}
			}
		}
	}

	.line {
		color: $u-light-color;
		font-size: 28rpx;
	}

	.wrap {
		background-color: #f2f2f2;

		.top {
			background-color: #ffffff;
			padding: 22rpx;
			padding-bottom: 0;

			.item {
				display: flex;
				font-size: 32rpx;
				line-height: 100rpx;
				align-items: center;
				border-bottom: solid 2rpx $u-border-color;

				.left {
					width: 180rpx;
				}

				input {
					flex: 1;
					text-align: left;
				}
			}

			.address {
				padding: 20rpx 0;

				.textarea {
					width: 100%;
					background-color: #f7f7f7;
					line-height: 60rpx;
					padding: 20rpx;
				}
			}
		}

		.bottom {
			margin-top: 20rpx;
			padding: 40rpx;
			padding-right: 0;
			background-color: #ffffff;
			font-size: 28rpx;

			.default {
				margin-top: 50rpx;
				display: flex;
				justify-content: space-between;
				border-bottom: solid 2rpx $u-border-color;
				line-height: 64rpx;

				.tips {
					font-size: 24rpx;
				}

				.right {
					switch {
						transform: scale(.8);
					}
				}
			}
		}
	}
</style>
